from bs4 import BeautifulSoup, Tag
from pool_v2.models import Week, Game


def create_week_from_html(html,date):
    week = Week(date=date)
    table = get_lines_table(html)
    week.save()    
    for game in create_games(table,week):
        game.save()

# This is for testing purposes only
def create_games_nodb(html,date):
    week = Week(date=date)
    table = get_lines_table(html)
    return create_games(table,week)

# need to add some error handling to make sure that away and home are properly formatted and line exists
def create_games(table,week):
    ret = []
    for game in game_rows(table):
        away = game.find_all('td')[column_index(table,'Opp')].string
        home = game.find_all('td')[column_index(table,'Team')].string
        line = parse_line(game.find_all('td')[column_index(table,'Line')].string)
        if (isinstance(away,unicode) and isinstance(home,unicode) and isinstance(line,int)):
            ret.append(Game(home=home,away=away,line=line,week_id=week.id))
    return ret


#if there is a ' in the string, we need to remove it
def parse_line(line):
    index = line.find("'")
    if len(line)>1 and (index == -1):
        return int(line)
    elif len(line)>1:
        return int(line[:index])
    else:
        return line
    
def get_lines_table(html):
    tables = html.find_all(lines_table)
    assert len(tables) == 1
    return tables[0]

# Grab all the tr tags in which the Site column is equal to 'H'
def game_rows(table):
    site_col=column_index(table,'Site')
    return filter(lambda row: 
                  row.find_all('td') and \
                  row.find_all('td')[site_col].string=='H', 
                  table.find_all('tr')[1:])


# Returns true when the HTML tag provided is the one that contains the lines
# Currently this just looks to see if the first row has a table headings of Date and Line
# An alternative way to do this would be to just grab the 7th table...but that would be suspectable to minor tweaks in their site
def lines_table(table):
    return (isinstance(table,Tag) and
            table.find('th',text='Date') and
            table == table.find('th',text='Date').find_parent("table") and
            table.find('th',text='Line') and
            table == table.find('th',text='Line').find_parent("table") and
            table.find('th',text='Site') and 
            table == table.find('th',text='Site').find_parent("table"))

    
def column_index(table,col):
    return table.find('tr').find_all('th').index(table.find('th',text=col))


# Gather the results
